# -*- coding: utf-8 -*-
from google.appengine.dist import use_library
use_library('django', '1.2')


import cgi, os
import hashlib, logging

from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import db

from gaesessions import get_current_session
from Cookie import SimpleCookie as cookie
from db import User
import misc

webapp.template.register_template_library('tag.filter')

class UserPage(webapp.RequestHandler):
	pseudo = ""
	uid = ""
	tpl_val = {}
	
	def __init__(self):
		self.pseudo = ""
		self.uid = ""
		self.tpl_val = {}
	
	def process(self):
		self.s = get_current_session()
		self.c = misc.get_cookie(self.request)

		try: 	self.pseudo = self.s['pseudo']
		except:	self.pseudo = self.c['pseudo'].value or ""
		try: 	self.pseudo = self.s['uid']
		except:	self.pseudo = self.c['uid'].value or ""

		self.tpl_val['pseudo'] = self.pseudo
		for x in self.request.arguments():
			self.tpl_val[x] = self.request.get(x, '')

	def show(self, page):
		path = os.path.join(os.path.dirname(__file__), 'views/%s'%page)
		self.response.out.write(template.render(path, self.tpl_val))

	def end_post(self, page, data):
		if 'X-Prototype-Version' in self.request.headers:
			self.response.headers['X-JSON'] = data
		else:
			self.redirect('/%s'%page)


class rep(UserPage):
	"""Manage user's contacts"""
	def get(self, todo):
		self.process()

		#TODO move to user handling API
		me = User.read(self.uid)
		if me is None:
			me = User()
			me.name = self.pseudo.lower()
			me.update()
			contact = []
		else:
			contact = me.contact

		self.tpl_val['contact'] = contact
		self.show('rep.html')

	def post(self, todo):
		"""Modification du répertoire"""
		self.process()
		
		me = User.read(self.uid)
		if me is None:
			self.redirect('/rep')
			return False

		if todo == "del":
			me.contact.remove(self.request.get('name'))
			me.update()
			self.end_post('rep', u'{"ok":true}')
			return True
		if todo == "add":
			if len(self.request.get('name')) < 4:
				self.end_post('/rep?e=badfield', '{"err":1}')
				return False
			me.contact.append(self.request.get('name'))
			me.update()
			self.end_post('rep', u'{"nom":"%s","err":0}'
										%self.request.get('name'))
			return True

		self.redirect('/rep')
		return False


class setting(UserPage):
  def get(self, todo):
	"""Information sur l'utilisateur."""
	self.process()

	me = User.read(self.uid)
	if me is None:
		me = User()
		me.name = self.pseudo.lower()
		me.update()

	self.tpl_val.update({
			'mail'	: me.mail,
			'im'	: me.im,
			'imPass': me.imPass	})
	if me.extPass:
		self.tpl_val['extPass'] = "Un mot de passe hashé"

	self.show('set.html')

  def post(self, todo):
	"""Edition des infos"""
	self.process()
	me = User.read(self.uid)

	if todo == 'email':
		# ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$
		me.mail = db.Email(self.request.get('email'))
		me.update()
		
	if todo == 'im':
		me.imPass = self.request.get('pass')
		me.update()

	if todo == 'ext':
		if self.request.get('pass') == 'Reset':
			me.extPass = ""
		else:
			me.extPass = hashlib.md5(
				self.request.get('pass').encode('utf-8')).hexdigest()
		me.update()

	self.redirect('/set')

class profil(UserPage):
  def get(self, who):
	"""Page de profil"""
	self.process()

	him = User.all().filter('name = ', who.lower()).get()
	if him is None:
		self.redirect('/?e=missingplayer')
		return False

	self.tpl_val.update({
		'type' : 'profil',
		'to'   : him.name, # needed to get the name on the write form
		'him'  : him, })

	self.show('profil.html')

class avatar(webapp.RequestHandler):
  def get(self, who):
	"""Affichage de l'avatar d'un joueur"""
	him = User.all().filter('name = ', who.lower()).get()
	avatar = him.avatar

	self.response.headers['Content-Type'] = 'image/gif'
	self.response.out.write(avatar)

